// 雅文学习课程的回调函数
export function EneteduCallBack() {
  if (window.enetedu_Timer) {
    clearInterval(enetedu_Timer);
  }
  window.enetedu_Count = 0;

  window.enetedu_Timer = setInterval(() => {
    window.enetedu_Count++;
    if (window.enetedu_Count > 10) {
      clearInterval(enetedu_Timer);
    }

    let curiframe = document.querySelector("iframe");
    if (curiframe) {
      let iFramDocument = curiframe.contentDocument;
      let currentVideoEl = iFramDocument.getElementsByTagName("video")[0];
      if (currentVideoEl) {
        currentVideoEl.playbackRate = 1.9; // 倍速
        currentVideoEl.volume = 0; // 音量0-1
        currentVideoEl.muted = true; // 静音
        currentVideoEl.paused && currentVideoEl?.play(); // 自动播放
      }
      console.log(
        "%cEneteduCallBack.js 25 [播放速度]",
        "color: #43bb88;font-size: 24px;",
        currentVideoEl.paused ? "暂停中" : "播放中",
        currentVideoEl.playbackRate
      );

      /**
       * 目的：自动播放下一个
       * 获取当前视频的id
       * 看当前播放元素的进度是否是100
       * 如果是的话，自动播放下一个元素
       */
      let ifSrc = document.getElementsByTagName("iframe")[0].src;
      if (ifSrc) {
        let res1 = ifSrc.split("?");
        let res2 = res1[1].split("&")[0];
        let currentVideoID = res2.split("=")[1]; // 获取当前视频的id

        let curProgressEl = document.getElementById(
          `courseware_${currentVideoID}`
        );
        if (curProgressEl) {
          let curProgressText = curProgressEl.innerText;
          let curProgressNum = parseFloat(
            curProgressText
              .replaceAll("[", "")
              .replaceAll("]", "")
              .replaceAll("%", "")
          );
          let parentNode = curProgressEl.parentNode;
          let nexePlayEl = parentNode.nextSibling;
          if (curProgressNum === 100 && nexePlayEl) {
            $(`#courseware_${currentVideoID}`).parent().next().click();
          }
        }
      }

      iFramDocument.getElementsByTagName("iframe")?.[0]?.remove();
      let divList = iFramDocument.getElementsByTagName("div");
      if (divList.length) {
        for (let i = 0; i < divList.length; i++) {
          if (divList[i].getAttribute("id")?.startsWith("layui-layer")) {
            divList[i].remove();
          }
        }
      }
    } else {
      console.log("未能获取到iframe元素");
    }
  }, 2000);
}
